package cloudspace.vm.javassist;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import cloudspace.vm.VM;

import javassist.CtBehavior;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.NotFoundException;

public class ClassAnalyzer
{

	public static Map<String, ClassOutline> inheritanceMap = new HashMap();

	/*
	 * public static void analyzeClass(CtClass classToAnalyze) { if
	 * (inheritanceMap.get(classToAnalyze.getName()) == null) {
	 * analyze0(classToAnalyze); } }
	 * 
	 * private static void analyze0(CtClass classToAnalyze) { ClassOutline
	 * cOutline = new ClassOutline(classToAnalyze);
	 * inheritanceMap.put(classToAnalyze.getName(), cOutline); }
	 */

	/*
	 * public static boolean checkRewrite(Object obj, String methodName) { if
	 * (obj != null) { Class<?> clazz = obj.getClass(); return
	 * checkRewrite(clazz, methodName); } return true; }
	 */
	public static boolean rewriteNeeded(Class clazz, String methodName)
	{
		VM currentVM = VM.getThreadTag();
		try
		{
			return rewriteNeeded(currentVM.getClassPool().get(clazz.getName()),
					methodName);
		}
		catch (NotFoundException e)
		{
			return true;
		}
	}

	public static boolean rewriteNeeded(CtClass clazz, String methodName)
	{
		try
		{
			if (clazz != null)
			{
				VM currentVM = VM.getThreadTag();
				// ClassOutline cOutline = inheritanceMap.get(clazz.getName());
				if (VM.getThreadTag().isLocalClass(clazz.getName()))
				{
					for (CtBehavior behavior : clazz.getDeclaredBehaviors())
					{
						String behaviorName = behavior.getLongName();
						if (behaviorName.endsWith(methodName))
						{
							return false;
						}
					}
					CtClass superClazz = null;
					superClazz = clazz.getSuperclass();
					return rewriteNeeded(superClazz, methodName);

				}
				else
				{
					return true;
				}
			}
		}
		catch (NotFoundException e)
		{
			;
		}
		return true;
	}

	public static boolean inSuperChain(CtClass declaringClass, String superName)
	{
		if (declaringClass != null)
		{
			try
			{
				if (declaringClass.getName().equals(superName))
				{
					return true;
				}
				else
				{
					return inSuperChain(declaringClass.getSuperclass(), superName);
				}
			}
			catch (NotFoundException e)
			{
				;
			}
		}
		return false;
	}
}
